let Sequelize = require('sequelize');
let {sequelize} = require('../sequelize.js');
const Op = Sequelize.Op;

let device_info = sequelize.define('device_info', {
      id: {
        type: Sequelize.BIGINT(11),
        primaryKey: true,
        allowNull: false,
        unique: true,
        autoIncrement: true
      },
      user_id: Sequelize.BIGINT(11),
      platform: Sequelize.STRING(100),
      uuid: Sequelize.STRING(35),
      ip_info: Sequelize.STRING(35),
      use_count: Sequelize.BIGINT(11),
      create_time: Sequelize.DATE
    },
    {
      timestamps: false, // 不要默认时间戳 数据库没有时间戳字段时，设置为false，否则报错  SequelizeDatabaseError: Unknown column 'createdAt' in 'field list'
      freezeTableName: true
    }
);

class DeviceObj {
  constructor() {
    this.device = device_info
  }

  async getAllDevices({user_id, platform, uuid, ip_info, use_count, dateTime, offset = 0, limit = 10}) {
    let where = {}
    if (user_id) where.content = {[Op.like]: `%${user_id}%`}
    if (platform) where.platform = {[Op.like]: `%${platform}%`}
    if (uuid) where.uuid = uuid
    if (ip_info) where.ip_info = {[Op.like]: `%${ip_info}%`}
    if (use_count) where.use_count = use_count
    if (dateTime) where.create_time = {[Op.between]: dateTime}
    let order = [['create_time', 'desc'], ['id', 'desc']]
    let total = await this.device.count({where})
    let list = await this.device.findAll({where, order, offset, limit})
    return {total, list}
  }

  getDeviceInfo({uuid = ''}, init = false) {
    return new Promise(async (resolve, reject) => {
      try {
        if (!uuid) return resolve("缺少uuid参数！")
        let mDevice = await this.device.findOne({where: {uuid: uuid}})
        if (mDevice) return resolve(mDevice)
        else if (init) return resolve(await this.createDevice({uuid}))
        else return resolve({})
      } catch (err) {
        console.error("getDeviceInfo", err)
        resolve("error")
      }
    })
  }

  async createDevice({user_id = 0, platform = '', use_count = 50, uuid = '', ip_info = ''}) {
    return this.device.create({
      id: 0,
      user_id: user_id,
      ip_info: ip_info,
      platform: platform,
      use_count: use_count,
      uuid: uuid
    })
  }

  updateDevice({user_id, ip_info, platform, use_count, uuid}, where) {
    if (!uuid) return Promise.resolve("缺少uuid参数！")
    if (!where) where = {uuid}
    return this.device.update({user_id, ip_info, platform, use_count}, {where})
  }

  async haveCount({uuid, platform, ip_info}, where = null) {
    try {
      if (!where) where = {uuid}
      let result = await this.device.findOne({where})
      if (!result) {
        let createResult = await this.createDevice({uuid, platform, ip_info})
        return createResult.use_count
      }
      return result.use_count
    } catch (err) {
      console.error("haveCount-error", err)
      return -1
    }
  }

  async useCount({uuid, platform, ip_info}) {
    if (!uuid) return {data: false, msg: '缺少uuid参数！'}
    let where = {uuid}
    let count = await this.haveCount({uuid, platform, ip_info}, where)
    if (count > 0) {
      let updateRes = await this.updateDevice({uuid, use_count: count - 1}, where)
      return {data: true, msg: `使用成功，剩余次数：${count - 1}！`}
    } else if (count == -1) return {data: false, msg: "500：server error"}
    else if (count == 0) return {data: false, msg: "50次试用次数已经用完！"}
  }
}

module.exports = {
  deviceObj: new DeviceObj(),
};
